package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.service.ChannelService;
import com.lkd.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Topic(TopicConfig.VMS_SUPPLY_TOPIC)
public class TaskSupplyMsgHandler implements MsgHandler {

    @Autowired
    private ChannelService channelService;

    /**
     * 完成补货工单,更新售货机库存
     * @param jsonMsg
     * @throws IOException
     */
    @Override
    public void process(String jsonMsg) throws IOException {
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        String innerCode = supplyContract.getInnerCode();
        List<SupplyChannel> supplyData = supplyContract.getSupplyData();

        List<ChannelEntity> entityList = channelService.getChannelesByInnerCode(innerCode);

        List<ChannelEntity> collect = entityList.stream().filter(e -> {
            for (SupplyChannel supplyChannel : supplyData) {
                if (e.getChannelId().equals(supplyChannel.getChannelId())) {
                    int capacity = e.getCurrentCapacity()+ supplyChannel.getCapacity();
                    e.setCurrentCapacity(capacity>e.getMaxCapacity() ? e.getMaxCapacity() : capacity);
                    e.setLastSupplyTime(LocalDateTime.now());
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList());

        for (ChannelEntity channelEntity : collect) {
            channelService.updateById(channelEntity);
        }
    }
}
